package consulService

import (
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
	"os"
	"os/signal"
	"syscall"
)

// RegisterServiceToConsul 注册服务到consul
func RegisterServiceToConsul(serviceName string, serviceID string, port int) {
	config := consulapi.DefaultConfig()
	config.Address = "127.0.0.1:8500"
	client, err := consulapi.NewClient(config)
	if err != nil {
		fmt.Println(err)
	}
	registration := &consulapi.AgentServiceRegistration{
		ID:      serviceID,
		Name:    serviceName,
		Port:    port,
		Address: "127.0.0.1",
	}
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		fmt.Println(err)
	}

	//优雅地注销服务
	go func() {
		ch := make(chan os.Signal, 1)
		signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
		<-ch
		err = client.Agent().ServiceDeregister(serviceID)
		if err != nil {
			fmt.Println(err)
		}
		os.Exit(0)
	}()
}
